import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface ProductDetailState {
  loading: boolean
  error: string | null
  data: any
}

const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null,
}

export const getProductDetail = createAsyncThunk(
  'productDetail/getProductDetail',
  async (touristRouteId: string, thunkAPI) => {
    thunkAPI.dispatch(productDetailSlice.actions.fetchStart())
    try {
      // const { data } = await axios.get(`${touristRouteId}`)
      const { data: dataobj } = await axios.get(
        `https://mock.mengxuegu.com/mock/64fc8254e70b8004a69ea29a/https:/mock.TrvalData/api/detail/${touristRouteId}`
      )

      const { data } = dataobj
      thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(data))
    } catch (error: any) {
      thunkAPI.dispatch(productDetailSlice.actions.fetchFail(error.message))
    }
  }
)

export const productDetailSlice = createSlice({
  name: 'productDetail',
  initialState,
  reducers: {
    fetchStart: (state: any) => {
      // return { ...state, loading: true };
      state.loading = true
    },
    fetchSuccess: (state: any, action: any) => {
      state.data = action.payload
      state.loading = false
      state.error = null
    },
    fetchFail: (state: any, action: PayloadAction<string | null>) => {
      //   const ddd = action.payload;
      state.loading = false
      state.error = action.payload
    },
  },
})
